package flexo.graphic;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.*;

import flexo.common.LogMsgType;
import flexo.graphic.entity.Entity;

public class Texture extends flexo.common.ReferenceCount
{
	/** The colour model including alpha for the GL image */
    private static ColorModel glAlphaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
            new int[] {8,8,8,8},
            true,
            false,
            ComponentColorModel.TRANSLUCENT,
            DataBuffer.TYPE_BYTE);
    
    /** The colour model for the GL image */
    private static ColorModel glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
            new int[] {8,8,8,0},
            false,
            false,
            ComponentColorModel.OPAQUE,
            DataBuffer.TYPE_BYTE);
	
	int textureID;
	int width;
	int height;

	public Texture(String path)
	{
		flexo.Kernel.log("flexo.graphic.Texture", "Creating texture from '"+path+"'");
		loadTexture(path);
	}
	
	/**
     * Creates an integer buffer to hold specified ints
     * - strictly a utility method
     *
     * @param size how many int to contain
     * @return created IntBuffer
     */
    protected static IntBuffer createIntBuffer(int size) {
      ByteBuffer temp = ByteBuffer.allocateDirect(4 * size);
      temp.order(ByteOrder.nativeOrder());

      return temp.asIntBuffer();
    }
    
    /** 
     * Load a given resource as a buffered image
     * 
     * @param ref The location of the resource to load
     * @return The loaded buffered image
     * @throws IOException Indicates a failure to find a resource
     */
    private BufferedImage loadImage(String ref) throws IOException 
    {
    	flexo.file.FileSystem fs = (flexo.file.FileSystem)flexo.Kernel.getSystem(flexo.file.FileSystem.ID);
    	BufferedImage bufferedImage = null;
    	
    	bufferedImage = ImageIO.read(new BufferedInputStream(fs.getStream(ref)));
    	return bufferedImage;
    }
    
    /**
     * Convert the buffered image to a texture
     *
     * @param bufferedImage The image to convert to a texture
     * @param texture The texture to store the data into
     * @return A buffer containing the data
     */
    private ByteBuffer convertImageData(BufferedImage bufferedImage,Texture texture) { 
        ByteBuffer imageBuffer = null; 
        WritableRaster raster;
        BufferedImage texImage;
        
        int texWidth = 2;
        int texHeight = 2;
        
        // find the closest power of 2 for the width and height

        // of the produced texture

        while (texWidth < bufferedImage.getWidth()) {
            texWidth *= 2;
        }
        while (texHeight < bufferedImage.getHeight()) {
            texHeight *= 2;
        }
        
        texture.height = texHeight;
        texture.width = texWidth;
        
        // create a raster that can be used by OpenGL as a source

        // for a texture

        if (bufferedImage.getColorModel().hasAlpha()) {
            raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,4,null);
            texImage = new BufferedImage(glAlphaColorModel,raster,false,new Hashtable<Entity,Entity>());
        } else {
            raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE,texWidth,texHeight,3,null);
            texImage = new BufferedImage(glColorModel,raster,false,new Hashtable<Entity,Entity>());
        }
            
        // copy the source image into the produced image

        Graphics g = texImage.getGraphics();
        g.setColor(new Color(0f,0f,0f,0f));
        g.fillRect(0,0,texWidth,texHeight);
        g.drawImage(bufferedImage,0,0,null);
        
        // build a byte buffer from the temporary image 

        // that be used by OpenGL to produce a texture.

        byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()).getData(); 

        imageBuffer = ByteBuffer.allocateDirect(data.length); 
        imageBuffer.order(ByteOrder.nativeOrder()); 
        imageBuffer.put(data, 0, data.length); 
        imageBuffer.flip();
        
        return imageBuffer; 
    }    
    
    /**
     * Load a texture into OpenGL from a image reference on
     * disk.
     *
     * @param resourceName The location of the resource to load
     * @param target The GL target to load the texture against
     * @param dstPixelFormat The pixel format of the screen
     * @param minFilter The minimising filter
     * @param magFilter The magnification filter
     * @return The loaded texture
     * @throws IOException Indicates a failure to access the resource
     */
    private void loadTexture(String resourceName)
    {
    	int target = GL11.GL_TEXTURE_2D;
        int dstPixelFormat = GL11.GL_RGBA; 
        int minFilter = GL11.GL_LINEAR; 
        int magFilter = GL11.GL_LINEAR;
        
        int srcPixelFormat = 0;
        
        // create the texture ID for this texture 

        this.textureID = createTextureID();         
        
        // bind this texture 

        GL11.glBindTexture(target, this.textureID); 
 
        
		try
		{
			BufferedImage bufferedImage = loadImage(resourceName);
		
			this.width = bufferedImage.getWidth();
			this.height = bufferedImage.getHeight();
	        
	        if (bufferedImage.getColorModel().hasAlpha()) {
	            srcPixelFormat = GL11.GL_RGBA;
	        } else {
	            srcPixelFormat = GL11.GL_RGB;
	        }
	
	        // convert that image into a byte buffer of texture data 
	
	        ByteBuffer textureBuffer = convertImageData(bufferedImage,this); 
	        
	        if (target == GL11.GL_TEXTURE_2D) 
	        { 
	            GL11.glTexParameteri(target, GL11.GL_TEXTURE_MIN_FILTER, minFilter); 
	            GL11.glTexParameteri(target, GL11.GL_TEXTURE_MAG_FILTER, magFilter); 
	        } 
	 
	        // produce a texture from the byte buffer
	
	        GL11.glTexImage2D(target, 
	                      0, 
	                      dstPixelFormat, 
	                      get2Fold(bufferedImage.getWidth()), 
	                      get2Fold(bufferedImage.getHeight()), 
	                      0, 
	                      srcPixelFormat, 
	                      GL11.GL_UNSIGNED_BYTE, 
	                      textureBuffer );
	        // unbinde the texture
	        GL11.glBindTexture(target, 0);
		} 
		catch (Exception e)
		{
			flexo.Kernel.log("flexo.graphic.Texture","Couldn't load texture: '" + resourceName + "'", LogMsgType.ERROR);
			flexo.Kernel.error();
		} 
    } 
    
    /**
     * Get the closest greater power of 2 to the fold number
     * 
     * @param fold The target number
     * @return The power of 2
     */
    private static int get2Fold(int fold) {
        int ret = 2;
        while (ret < fold) {
            ret *= 2;
        }
        return ret;
    }
	
	/**
     * Create a new texture ID 
     *
     * @return A new texture ID
     */
    private static int createTextureID() 
    { 
       IntBuffer tmp = createIntBuffer(1); 
       GL11.glGenTextures(tmp); 
       return tmp.get(0);
    }

	/**
	 * @return Texture ID for this image
	 */
	int getTextureID()
	{
		return textureID;
	}
	
	/**
	 * Binds this image
	 */
	public void bind()
	{		
		GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
	}

	protected void destroy()
	{
		IntBuffer scratch = BufferUtils.createIntBuffer(1);
		scratch.put(0, textureID);
		GL11.glDeleteTextures(scratch);
	}
}